package com.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.dubbo.server.enums.IdType;
import com.dubbo.server.pojo.FollowUser;
import com.dubbo.server.service.IdService;
import com.mongodb.client.result.DeleteResult;
import com.tanhua.dubbo.server.api.VideoApi;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

@Service(version = "1.0.0")
@Slf4j
public class VideoApiImpl implements VideoApi {


    @Autowired
    private IdService idService;
    private static final String VIDEO_FOLLOW_USER_KEY_PREFIX = "VIDEO_FOLLOW_USER_";

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    RedisTemplate<String,String> redisTemplate;

    /**
     * 发布小视频
     *
     * @param video
     * @return
     */
    @Override
    public String saveVideo(Video video) {
        try {
            //校验
            if(!ObjectUtil.isAllNotEmpty(video.getUserId(), video.getPicUrl(), video.getVideoUrl())){
                return null;
            }

            //设置id
            video.setId(ObjectId.get());
            video.setVid(this.idService.createId(IdType.VIDEO));

            //发布时间
            video.setCreated(System.currentTimeMillis());

            //保存到Mongodb中
            this.mongoTemplate.save(video);

            String a= video.getId().toHexString();
            return a;
        } catch (Exception e) {
            log.error("小视频发布失败~ video = " + video, e);
        }
        return null;
    }
    @Override
    public PageInfo<Video> queryVideoList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Video> videoPageInfo = new PageInfo<>();
        videoPageInfo.setPageNum(page);
        videoPageInfo.setPageSize(pageSize);
        String redisKey = "QUANZI_VIDEO_RECOMMEND_" + userId;
        String s = redisTemplate.opsForValue().get(redisKey);
        ArrayList<Long> longs = new ArrayList<>();
        int recommendCount=0;
        if(StrUtil.isNotEmpty(s))
        {

            List<String> vidList = StrUtil.split(s, ',');
            int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);
            int startIndex = startEnd[0]; //开始
            int endIndex = Math.min(startEnd[1], vidList.size()); //结束

            for (int i = startIndex; i < endIndex; i++) {
                longs.add(Convert.toLong(vidList.get(i)));
            }
            recommendCount = vidList.size();
            if(CollUtil.isEmpty(longs))
            {
                int i = PageUtil.totalPage(recommendCount, pageSize);
               /* PageRequest pageRequest = PageRequest.of(page - i - 1, pageSize, Sort.by(Sort.Order.desc("created")));
                Query query = new Query()
                        .with(pageRequest);*/
                Query query = new Query().with(Sort.by(Sort.Order.desc("created"))).with(PageRequest.of(page - i - 1,pageSize));
                List<Video> videos = mongoTemplate.find(query, Video.class);
                videoPageInfo.setRecords(videos);
                return videoPageInfo;
            }
            List<Video> vid = mongoTemplate.find(new Query(Criteria.where("vid")
                    .in(longs)), Video.class
            );
            videoPageInfo.setRecords(vid);
            return videoPageInfo;


        }
        return null;


    }

    @Override
    public Video queryVideoById(String videoId) {

        Video byId = mongoTemplate.findById(new ObjectId(videoId), Video.class);
        return byId;
    }

    @Override
    public Boolean followUser(Long userId, Long followUserId) {
        if(!ObjectUtil.isAllNotEmpty(userId,followUserId))
            return false;
        if(isFollowUser(userId,followUserId))
            return false;
        try {
            FollowUser followUser = new FollowUser();
            followUser.setId(ObjectId.get());
            followUser.setUserId(userId);
            followUser.setFollowUserId(followUserId);
            followUser.setCreated(System.currentTimeMillis());
            mongoTemplate.save(followUser);
            String redisKey = this.getVideoFollowUserKey(userId);
            String hashKey = String.valueOf(followUserId);
            redisTemplate.opsForHash().put(redisKey,hashKey,"1");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;

    }

    @Override
    public Boolean disFollowUser(Long userId, Long followUserId) {
        if(!ObjectUtil.isAllNotEmpty(userId,followUserId))
            return false;
        if(!isFollowUser(userId,followUserId))
            return false;
        try {
            Query query = Query.query(Criteria.where("userId").is(userId)
                    .and("followUserId").is(followUserId));
            DeleteResult remove = mongoTemplate.remove(query, FollowUser.class);

            if(remove.getDeletedCount()>0) {
                String redisKey = this.getVideoFollowUserKey(userId);
                String hashKey = String.valueOf(followUserId);
                Long delete = redisTemplate.opsForHash().delete(redisKey, hashKey);
                return true;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;


    }

    @Override
    public Boolean isFollowUser(Long userId, Long followUserId) {
        String redisKey = this.getVideoFollowUserKey(userId);
        String hashKey = String.valueOf(followUserId);
        Boolean aBoolean1 = redisTemplate.opsForHash().hasKey(redisKey, hashKey);
       return aBoolean1;



    }
    private String getVideoFollowUserKey(Long userId) {
        return VIDEO_FOLLOW_USER_KEY_PREFIX + userId;
    }
}